<template>
  <el-card class="box-card el-card-flex">
    <div slot="header" class="clearfix">
			<span>
				<i class="el-icon-position"></i>
				流程提交
			</span>
		</div>
    <!-- 表单 -->
    <div class="text item">
        <el-form :inline="true" :model="AdvancedQuery" class="demo-form-inline" style="float: left;height:43px">
          <!-- 左侧搜索按钮 -->
          <el-form-item label="">
            <el-input clearable v-model="textSearch" placeholder="请输入请假单编码" style="width:240px;"
            @keyup.enter.native="getLists" @clear="getLists">
            <el-button slot="append" icon="el-icon-search" @click="getLists"></el-button>
          </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="advancedQuery">
              高级查询
              <i class="el-icon-magic-stick"></i>
            </el-button>
          </el-form-item>
          <!-- 右侧操作按钮 -->
          <el-form-item style="float:right">
            <el-button @click="handleadd" type="primary" plain>
                新增
                <i class="el-icon-plus"></i>
            </el-button>
          </el-form-item>
        </el-form>
      <!-- 表格 -->
      <div class="el-flex el-box-column">
        <el-table :data="tableData" ref="tableData"  height="100%" style="width: 100%" border stripe>
          <el-table-column show-overflow-tooltip sortable min-width="150" align="center" prop="applyCode" label="请假单编码"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="100" prop="applyDept" label="部门"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="140" prop="applyDesc" label="请假事由"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="147" align="center" prop="startDate" label="开始日期"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="147" align="center" prop="endDate" label="结束日期"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="100" align="center" prop="days" label="请假天数"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="147" prop="applyDate" align="center" label="申请日期"></el-table-column>
          <el-table-column show-overflow-tooltip sortable prop="approveStatusDesc" min-width="100" align="center" label="审批状态"></el-table-column>
          <el-table-column show-overflow-tooltip sortable min-width="90" prop="createdBy" label="创建人"></el-table-column>
          <el-table-column show-overflow-tooltip sortable prop="control" align="center" label="操作" width="180" fixed="right">
            <template slot-scope="scope">
              <el-button class="td-btn-icon" :disabled='scope.row.approveStatusDesc == "审批中"' type="text" icon="el-icon-edit" title="编辑" @click="handleEdit(scope.$index, scope.row)"></el-button>
              <el-button class="td-btn-icon" :disabled='scope.row.approveStatusDesc == "审批中" ||scope.row.approveStatusDesc == "审批通过"'  type="text" icon="el-icon-position" title="提交" @click="submission(scope.$index, scope.row)"></el-button>
              <el-button class="td-btn-icon" :disabled='scope.row.approveStatusDesc == "起草"' type="text" icon="el-icon-monitor" title="监控" @click="monitor(scope.$index, scope.row)"></el-button>
              <el-button class="td-btn-icon" :disabled='scope.row.approveStatusDesc == "审批通过" ||scope.row.approveStatusDesc == "撤回"  ||scope.row.approveStatusDesc == "起草"' type="text" icon="el-icon-refresh-left" title="撤回" @click="withdraw(scope.$index, scope.row)"></el-button>
              <el-button class="td-btn-icon" :disabled='scope.row.approveStatusDesc == "审批中"' type="text" icon="el-icon-delete" title="删除" @click="handDelete(scope.$index, scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页表格 -->
        <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
      <!-- 高级查询抽屉式弹框 -->
    <el-drawer
      title="高级查询"
      :visible.sync="dialogVisibleSearch" 
      :before-close="searchClose"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
			:wrapperClosable="false"
      :close-on-press-escape="false"
    >
      <div class="demo-drawer__content el-box-column" style="height: 100%; margin-right:10px;">
            <el-form label-width="130px" ref="AdvancedQuery" :model="AdvancedQuery" class="el-flex">
              <el-form-item label="请假单编码" prop="applyCode">
                  <el-col :span="24">
                    <el-input  placeholder="请输入请假单编码" v-model="AdvancedQuery.applyCode" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="部门" prop="applyDept" >
                  <el-col :span="24">
                    <el-input  placeholder="请输入部门" v-model="AdvancedQuery.applyDept" clearable></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="请假事由" prop="applyDesc" >
                  <el-col :span="24">
                    <el-input placeholder="请输入请假事由" v-model="AdvancedQuery.applyDesc" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
               <el-form-item label="申请日期开始时间" prop="startDate" >
                  <el-col :span="24">
                    <el-date-picker v-model="AdvancedQuery.startDate" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"></el-date-picker>
                </el-col>
              </el-form-item>
              <el-form-item label="申请日期结束时间" prop="endDate" >
                  <el-col :span="24">
                    <el-date-picker v-model="AdvancedQuery.endDate" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"></el-date-picker>
                </el-col>
              </el-form-item>
              <el-form-item label="审批状态" prop="approveStatus" >
                  <el-col :span="24">
                    <el-select v-model="AdvancedQuery.approveStatus" clearable placeholder="请选择">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.approveStatus">
                      </el-option>
                    </el-select>
                </el-col>
              </el-form-item>
            </el-form>
            <div class="demo-drawer__footer" style="text-align: right; margin-bottom: 10px; padding-right:10px;">
                <el-button type="primary" @click="getLists">确定<i class="el-icon-document-checked el-icon--right"></i></el-button>
                <el-button @click="dialogVisibleSearch = false">取消
                  <i class="el-icon-refresh-left"></i>
                </el-button>
            </div>
          </div>
    </el-drawer>
        <!-- 新增或修改编辑弹框 -->
        <el-dialog :title="modalTitle" :visible.sync="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="handleAddClose" class="elAdded">
          <div class="container" >
            <el-form label-width="100px" ref="editData" :model="editData" :rules="ruleValidate">
              <el-form-item label="请假单编码" prop="applyCode" v-show="isdisplay" >
                <el-col :span="18">
                   <span v-model="editData.applyCode" auto-complete="off">{{this.editData.applyCode}}</span>
                </el-col>
              </el-form-item>
              <el-form-item label="状态编码" prop="approveStatus" v-show="isStatus" >
                <el-col :span="18">
                  <el-input v-model="editData.approveStatus" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="状态" prop="approveStatusDesc" v-show="isStatus" >
                <el-col :span="18">
                  <el-input v-model="editData.approveStatusDesc" auto-complete="off"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="部门" prop="applyDept">
                <el-col :span="18">
                    <el-input v-model="editData.applyDept" placeholder="请输入内容" clearable></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="请假事由" prop="applyDesc">
                <el-col :span="18">
                  <el-input type="textarea" v-model="editData.applyDesc" :rows="2" placeholder="请输入内容" ></el-input>
                </el-col>
              </el-form-item>
              <div style="display: flex;">
                <el-form-item label="开始日期" prop="startDate">
                  <el-col  :span="10">
                    <el-date-picker :picker-options='startDate' @blur='blur' v-model="editData.startDate" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"></el-date-picker>
                  </el-col>
                </el-form-item>
                <el-form-item label="结束日期" prop="endDate">
                  <el-col :span="14">
                      <el-date-picker :picker-options='endDate'  @blur='blur' v-model="editData.endDate" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-col>
                </el-form-item>
              </div>
              <el-form-item label="请假天数" prop="days">
                <el-col :span="18">
                  <span v-model="editData.days" auto-complete="off">{{this.editData.days}}</span>
                </el-col>  
              </el-form-item>
              <el-form-item label="申请日期" prop="applyDate">
                <el-col :span="18">
                  <span v-model="editData.applyDate" auto-complete="off">{{this.editData.applyDate}}</span>
                </el-col>  
              </el-form-item>
              <el-form-item label="创建人" prop="createdBy" v-show="isdisplay">
                <el-col :span="18">
                   <span v-model="editData.createdBy" auto-complete="off">{{this.editData.createdBy}}</span>
                </el-col>
              </el-form-item>
            </el-form>
          </div>
          <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="handleSubm">提交<i class="el-icon-document-checked el-icon--right"></i></el-button>
              <el-button type="primary" @click="handleCheck">保存<i class="el-icon-document-checked el-icon--right"></i></el-button>
              <el-button type="danger" @click="handleCloseCheck(false)">关闭 <i class="el-icon-close"></i></el-button>
          </span>
        </el-dialog>
        <!-- 请假单详情页弹框 -->
        <el-dialog :title="modalTitle" :visible.sync="detailsDialog" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="handleAddClose" class="elAdded">
            <div class="container" >
              <el-form label-width="160px" ref="editData" :model="editData" :rules="ruleValidate">
              <el-form-item label="请假单编码：" prop="applyCode" v-show="isdisplay" >
                <el-col :span="18">
                   <span v-model="editData.applyCode" auto-complete="off">{{this.editData.applyCode}}</span>
                </el-col>
              </el-form-item>
              <el-form-item label="状态编码：" prop="approveStatus" v-show="isStatus" >
                <el-col :span="18">
                  <span v-model="editData.approveStatus" auto-complete="off">{{this.editData.approveStatus}}</span>
                </el-col>
              </el-form-item>
              <el-form-item label="状态：" prop="approveStatusDesc" v-show="isStatus" >
                <el-col :span="18">
                  <span v-model="editData.approveStatusDesc" auto-complete="off">{{this.editData.approveStatusDesc}}</span>
                </el-col>
              </el-form-item>
              <el-form-item label="部门：" prop="applyDept">
                <el-col :span="18">
                  <span v-model="editData.applyDept" auto-complete="off">{{this.editData.applyDept}}</span>
                </el-col>
              </el-form-item>
              <el-form-item label="请假事由：" prop="applyDesc">
                <el-col :span="18">
                  <span v-model="editData.applyDesc" auto-complete="off">{{this.editData.applyDesc}}</span>
                </el-col>
              </el-form-item>
              <div style="display: flex;">
                <el-form-item label="开始日期：" prop="startDate">
                  <el-col>
                    <span v-model="editData.startDate" auto-complete="off">{{this.editData.startDate}}</span>
                  </el-col>
                </el-form-item>
                <el-form-item label="结束日期：" prop="endDate">
                  <el-col>
                    <span v-model="editData.endDate" auto-complete="off">{{this.editData.endDate}}</span>
                    </el-col>
                </el-form-item>
              </div>
              <el-form-item label="请假天数：" prop="days">
                <el-col :span="18">
                  <span v-model="editData.days" auto-complete="off">{{this.editData.days}}</span>
                </el-col>  
              </el-form-item>
              <el-form-item label="申请日期：" prop="applyDate">
                <el-col :span="18">
                  <span v-model="editData.applyDate" auto-complete="off">{{this.editData.applyDate}}</span>
                </el-col>  
              </el-form-item>
              <el-form-item label="创建人：" prop="createdBy" v-show="isdisplay">
                <el-col :span="18">
                   <span v-model="editData.createdBy" auto-complete="off">{{this.editData.createdBy}}</span>
                </el-col>
              </el-form-item>
            </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button type="danger" @click="handleCloseCheck(false)">关闭 <i class="el-icon-close"></i></el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </el-card>
</template>
<script>
import {Tree, Dialog, Table, TableColumn, Pagination, MessageBox, Message, Drawer} from "element-ui";
export default {
  name: "trainInvestigate",
  components: {
    "el-table": Table, //表格
    "el-table-column": TableColumn, //表格列
    "el-pagination": Pagination, //分页
    "el-dialog": Dialog, //对话框
    "el-pagination": Pagination, //分页
    'el-drawer': Drawer //抽屉
  },
  data() {
    var dataList={
        applyCode: "",
        applyDept: "",
        applyDesc: "",
        days:0,
        applyDate:"",
        endDate: "",
        approveStatus:"A",
        approveStatusDesc:"起草",
        createdBy: "",
        startDate: ""
    }
    return {
      textSearch:'', //搜索按钮
      dialogVisible: false, //新增或修改对话框弹出层
      detailsDialog: false, //新增或修改对话框弹出层
      dialogVisibleSearch:false, //高级查询对话框弹出层
      total:0,//总条数
      pageSize: 20, //每页展示条数
      currentPage: 1, //默认显示页数
      modalTitle: "", //新增或修改弹出层标题
      AdvancedQuery:{},
      endDate: "",
      searchData:'', //存储搜索数据
      isStatus:false, //状态隐藏
      isdisplay:true, //是否显示请假单编码
      tableData: [],
      AdvancedQuery:{
        applyCode: "",
        applyDept: "",
        applyDesc: "",
        endDate: "",
        approveStatus:"",
        startDate: ""
    }, 
      dataList: JSON.parse(JSON.stringify(dataList)), // 新增/编辑弹框里的model,用于重置表单
      editData: JSON.parse(JSON.stringify(dataList)), //将一个对象或者数组转为json字符串，然后将数据转换为 JavaScript 对象。
      options:[
          {
          approveStatus: 'A',
          label: '起草'
        }, {
          approveStatus: 'D',
          label: '驳回'
        }, {
          approveStatus: 'E',
          label: '审批通过'
        }, {
          approveStatus: 'R',
          label: '撤回'
        }, {
          approveStatus: 'C',
          label: '审批中'
        }
      ],
      // 表单验证是否为空
      ruleValidate: {
       startDate: [{
            required: true,

            message: "开始时间不能为空",

            trigger: "blur"
          }],
        endDate: [{
            required: true,

            message: "结束时间不能为空",

            trigger: "blur"
          }],
          applyDesc: [{
            required: true,

            message: "请假事由不能为空",

            trigger: "blur"
          }],
      },
      //账户生效时间不能早于今天
      startDate: {
        disabledDate: time => {
          if (this.editData.endDate) {
            return (
              time.getTime() > new Date(this.editData.endDate).getTime()//不能选择的时间值
            )
          }
        }
      },
      // 账户失效时间不能早于账户生效时间
      endDate: {
        disabledDate: time => {
          if (this.editData.startDate){
            return (
              time.getTime() < new Date(this.editData.startDate).getTime() - 8.64e7 // 加- 8.64e7则表示包当天
            )
          } 
        }
      }
    };
  },
  created(){
    window.onresize = () => {
      this.$refs.tableData.doLayout()
    }
  },
  mounted () {
    this.getLists();
    this.getTime()
  },
  methods: {
    // 新增
    handleadd() {
      this.isdisplay = false;
      this.dialogVisible = true;
      this.modalTitle = "新增请假单";
      this.editData = JSON.parse(JSON.stringify(this.dataList))
  },
   // 获取列表数据源
  getLists(){
    console.log( this.AdvancedQuery)
     let data = {
          "page": this.currentPage,
          "pagesize": this.pageSize,
        };
        if (this.dialogVisibleSearch) { //高级查询
           data.type = 2;
           Object.assign(data, this.AdvancedQuery);
        } else { //模糊查询 
          data.type = 1;
          data.expression = this.textSearch;
        }
      data = this.filterInvalid(data); //过滤无效参数
      this.axios.post(`/demo/findList/${this.currentPage}/${this.pageSize}`,data).then(res =>{ 
      console.log(res)
      this.tableData = res.data.data.records
      this.total = res.data.data.total
      this.dialogVisibleSearch = false;
      setTimeout(() => {
          this.$refs.tableData.doLayout(); //表格刷新以后，重绘表格宽度
      }, 0)
    })
  },
  //编辑弹框确认 -- 增改
      handleCheck(index,row) {
        console.log(this.editData)
        this.$refs.editData.validate(valid => {
          if (valid) {
            this.dialogVisible = false;
            let sendDatas = this.filterInvalid(this.editData);
            this.axios.post('/demo/saveOrUpdate',sendDatas).then(res => {
              if (res.data.code === 10000) {
                console.log(res)
                this.getLists()
                Message.success("保存成功")
              }
            }).catch(error =>{
              Message.success("保存失败")
            })
          }
        });
    },
    //新增弹框内的提交按钮
    handleSubm(index,row){
      this.$refs.editData.validate(valid => {
          if (valid) {
            this.dialogVisible = false;
            let sendDatas = this.filterInvalid(this.editData);
            //首次保存
            this.axios.post('/demo/saveOrUpdate',sendDatas).then(res => {
              if(res.data.code === 10000){
                // var instanceId = res.data.data.records.instanceId?res.data.data.records.instanceId:"";
                this.editData.applyId = res.data.data;//存储首次保存成功后返回的主键
                //首次报存成功后提交
                  this.axios.post('/workFlow/processSubmit?processName=demo&isSkip=Y',{
                    days:sendDatas.days,
                  }).then(res =>{
                    console.log(res)
                    if(res.data.code = 10000){
                     
                      let row = this.editData
                      row.instanceId = res.data.data.instanceId
                      row.approveStatusDesc = '审批中'
                      row.approveStatus = 'C'
                       //提交成功后再次保存（审批状态）
                      this.axios.post('/demo/saveOrUpdate',this.filterInvalid(row)).then(res => {
                          if (res.data.code === 10000) {
                            
                            console.log(res)
                            this.getLists()//刷新表格
                            Message.success("提交成功")
                          }
                        })
                    }
                  }).catch(error =>{
                    Message.success("提交失败")
                  })
              }
            })
          }
        });
    },
    //提交
    submission(index, row){
       var instanceId = row.instanceId?row.instanceId:"";
       this.axios.post('/workFlow/processSubmit?processName=demo&instanceId=' + instanceId + '&isSkip=Y',{
        days:row.days,
      }).then(res =>{
        console.log(res)
        if(res.data.code = 10000){
          row.instanceId = res.data.data.instanceId
          row.approveStatusDesc = '审批中'
          row.approveStatus = 'C'
          this.axios.post('/demo/saveOrUpdate',row).then(res => {
              if (res.data.code === 10000) {
                
                console.log(res)
                this.getLists()
                Message.success("提交成功")
              }
            })
        }
      }).catch(error =>{
        Message.success("提交失败")
      })

// this.axios({
//     method: 'post',
//     url: '/workFlow/processSubmit',
//     params:{
//     processName: "demo",
//     instanceId:row.instanceId?row.instanceId:""
//     },
//     data: {
//       days:row.days
//     }
//   }).then(res =>{
//         console.log(res)
        
//       })
     
    },
    //删除数据
    handDelete(index, row){
      MessageBox.confirm('您是否确定删除选中内容', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            this.axios.delete(`/demo/delete/${row.applyId}`)
          .then(res =>{
            if(res.data.code === 10000){
              this.getLists()
              Message.success('删除成功')
              console.log(res)
            }
          }).catch(error =>{
             Message.info('删除失败')  
            console.log(error)
          })
        }).catch(() => {
          Message.info('已取消删除')       
        });
        
    },
    //撤回
    withdraw(index,row){
      this.axios.post('workFlow/completeTask',{
        opcode:'1002',
        instanceId:row.instanceId
      }).then(res =>{
         console.log(res)
          if(res.data.code = 10000){
             row.approveStatusDesc = '撤回'
             row.approveStatus = 'R'
            row.instanceId = res.data.data.instanceId
            this.axios.post('/demo/saveOrUpdate',row).then(res => {
                if (res.data.code === 10000) {
                  console.log(res)
                  this.getLists()
                  Message.success("撤回成功")
                }
              }).catch(error =>{
                Message.success("撤回失败")
              })
          }
       })
    },
    //监控
    monitor(index,row){
      console.log(row)
       this.$router.push({
          name: 'processMonitor',
          params: row
        })
    },
    handleEdit(index, row) {
      //编辑
      this.editData = JSON.parse(JSON.stringify(row));
      
      this.isdisplay=true; //显示请假单编码样式
      if(row.approveStatusDesc === '审批中' || row.approveStatusDesc === '审批通过'){
        this.modalTitle = "请假单详情"
        this.detailsDialog = true
      }else{
        this.modalTitle = "编辑用户信息"
        this.dialogVisible = true 
      }
      
    },
   // 弹框关闭 × 按钮 
    handleCloseCheck () {
      this.handleAddClose();
      this.$refs.editData.resetFields(); //重置校验
    },
    // 关闭新增授权按钮
    handleAddClose() {
      this.dialogVisible = false;
      this.detailsDialog = false;
      this.$refs.editData.resetFields(); //重置校验
    },
   
    //获取本地当前时间
    getTime(){
      var date = new Date();
      var year =  date.getFullYear();
      var month =  date.getMonth()+1;
      var strDate =  date.getDate();
      if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
      var today = year + '-' + month + '-' + strDate;
      
      this.dataList.applyDate= today
    },
      //计算两个时间段中间有多少天
    blur(){
      var star = this.editData.startDate;
      var end = this.editData.endDate
      var date1=new Date(star);
      var date2=new Date(end);
      var date=(date2.getTime()-date1.getTime())/(1000*60*60*24)+1;/*不用考虑闰年否*/
      if(star && end){
         this.editData.days = date
      }else{
        return
      }
    },
    // 高级查询
    advancedQuery(){
      this.dialogVisibleSearch = true
      this.AdvancedQuery = JSON.parse(JSON.stringify(this.dataList))
      this.AdvancedQuery.approveStatusDesc=''
      this.AdvancedQuery.applyDate=''
    },
    
    // 每页条数
		handleSizeChange(val) {
      this.pageSize = val
      this.getLists()
    },
    // 当前页数
    handleCurrentChange(val) {
      this.currentPage = val
			this.getLists()
		},
    
    // 高级查询弹框关闭
		searchClose () {
      this.dialogVisibleSearch = false
		},
    
  /* 过滤无效数据*/
      filterInvalid(dataSource){
        let validData = {};
        let jsonData = JSON.stringify(dataSource);
        for(let k in dataSource){
          let data = dataSource[k];
          if(data != "" && data != null && data != undefined && jsonData!= "{}" && jsonData!= "[]"){
            validData[k] = data;
          }
        }
        return validData;
      },
    
    
   
  }
};
</script>
<style lang="scss">
.el-table {
  th {
    padding: 6px 0;
  }
  td {
    padding: 6px 0;
  }
}
.el-table__row {
  .cell {
    a {
      color: #409eff;
    }
  }
}
.elAdded .el-date-editor.el-input, .el-date-editor.el-input__inner{
  width:190px;
}
.display{
  display:none;
}
</style>
